package lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author fei
 * @date 2023/1/7 15:05
 * @description 从 ReentrantLock 卖票 demo 演示公平和非公平现象
 */
public class SaleTicketDemo {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        new Thread(() -> {for (int i = 0; i < 55; i++) ticket.sale();}, "a").start();
        new Thread(() -> {for (int i = 0; i < 55; i++) ticket.sale();}, "b").start();
        new Thread(() -> {for (int i = 0; i < 55; i++) ticket.sale();}, "c").start();
    }

}

/**
 * 资源类，模拟 3 个售票员卖完 50 张票
 */
class Ticket{

    private int number = 50;
    /**
     * 默认为 非公平锁
     */
    ReentrantLock lock = new ReentrantLock();

    public void sale(){
        lock.lock();
        try{
            if (number > 0){
                System.out.println(Thread.currentThread().getName() + "卖出第：\t" +
                        (number--) + "\t 还剩下：" + number);
            }
        } finally {
            lock.unlock();
        }
    }

}
